<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
include __ROOT__ . "../include/function/upload.php";
include __ROOT__ . "../www/Interface/www/op/functions.php";
include __ROOT__ . "../www/Meeting/lib/libraries/cfg.php";
/**
 *
 * @author yxx
 * @date 2017-10-12
 */
class Device extends MY_Controller {

	    public function __construct() {
	        parent::__construct();
	        $this->load->model('M_device');
	        $this->load->model('M_device_report');
	        $this->load->model('M_device_repairtask');
	        $this->load->model('M_device_task_sub');
	        $this->load->model('M_device_inspecttask');
	    }
	    
	/**上报故障信息接口
	 *@param $PID
	*/
	public function save_device_report(){
		$userid = $this->input->get_post("userid", true);//上报人id
		$devid = $this->input->get_post("devid", true);//设备id
		$typeid = $this->input->get_post("typeid", true);//设备类型ID
		$file = $_FILES;//图片
		// $file = $this->input->get_post("file", true);
		// $voice = $this->input->get_post("voice", true);//语音
		$remark = $this->input->get_post("remark", true);//留言
		$grid_id = $this->input->get_post("gridid", true);//网格id
		$x = $this->input->get_post("x", true);//X轴
		$y = $this->input->get_post("y", true);//Y轴
		$sql = "SELECT device_name as name FROM t_device WHERE device_id={$devid}";
		$info = $this->db->query($sql)->row_array();
		if(empty($userid)){
		       exit(json_encode(array('code'=>1,'info'=>'用户pid不能为空')));
		}
		if(empty($devid)){
		       exit(json_encode(array('code'=>1,'info'=>'设备ID不能为空')));
		}
		if(empty($typeid)){
		       exit(json_encode(array('code'=>1,'info'=>'设备类型id不能为空')));
		}
		if(!empty($devid)){
			$sql = "SELECT device_status FROM t_device WHERE device_id={$devid}";
			$status = $this->db->query($sql)->row_array();
			if($status['device_status']<>1){
				exit(json_encode(array('code'=>1,'info'=>'此设备已报修')));
			}
		}
	
		$sqlper="select user_name from t_user where user_id='{$userid}'";
		$per = $this->db->query($sqlper)->row_array();
		$data=array(
			'report_file'=>$file,
			'report_voice'=>$voice,
			'report_remark'=>$remark,
			'report_addtime'=>time(),
			'report_status'=>1,
			'grid_id'=>$grid_id,
			'device_id'=>$devid,
			'device_type_id'=>$typeid,
			'report_user_id'=>$userid,
			'report_user_name'=>$per['user_name'],
			'x'=>$x,
			'y'=>$y,
			);
		$insert_id = $this->M_device_report->saveData($data);
			if($insert_id){
				if($devid){
					$upsql = "UPDATE t_device SET device_status=1 WHERE device_id ='{$devid}'";
					$this->db->query($upsql);
					$sqlp = "select device_id,wx_post_id from t_device WHERE device_id ='{$devid}'";
					$postid = $this->db->query($sqlp)->row_array();
					$sqlpy = "select post_type_id from t_post where post_id='{$postid['wx_post_id']}'";
					$py = $this->db->query($sqlpy)->row_array();
					$data1=array(
							'repairtask_time'=>time(),
							'repairtask_result'=>0,
							'status'=>0,
							'repairtask_is_open'=>0,
							'repairtask_is_notice'=>0,
							'report_id'=>$insert_id,
							'repairtask_user_id'=>1
							);
					$insert_id1 = $this->M_device_repairtask->saveData($data1);
					//下发维修任务给维修岗位在线人员,3分钟无人在线就通知岗位负责人,10分钟无人接收就通知车间负责人
					if($py==1){
						$users = self::gettaskuser1($postid['wx_post_id']);
					}else{
						$users = self::gettaskuser2($postid['wx_post_id']);
					}
					if(!empty($users)){
						if($insert_id1){
							foreach ($users as $k => $v) {
								$sqldet="select a.department_id,b.department_name from t_user a left join t_department b on b.department_id=a.department_id where a.user_id='{$v['user_id']}'";
								$det = $this->db->query($sqldet)->row_array();
								$data2=array(
									'repairtask_id'=>$insert_id1,
									'the_task_type'=>2,
									'user_id'=>$v['user_id'],
									'task_status'=>0,
									'task_time'=>0, //接收时间
									'task_addtime'=>time(),//创建时间
									'task_endtime'=>0,
									'task_remark'=>''
									);
								$insert_id2 = $this->M_device_task_sub->saveData($data2);
								$url ="#";//维修任务列表
								$type ="devicemaintainnotice";
								$content = $remark;
								$title = $info['name'].'设备的维修任务';
								$send = method::sendmess('admin',$content,$v['user_account'],$title,$url,$type);
							}
							//修改任务状态
							$updsql = "UPDATE t_device_repairtask SET status=1,repairtask_is_open=1 WHERE repairtask_id ='{$insert_id1}'";
							$this->db->query($updsql);
						}
					}
				}
			exit(json_encode(array('code'=>0,'info'=>'故障上报成功')));
		}else{
			exit(json_encode(array('code'=>1,'info'=>'故障上报失败')));
		}
	}

	private function gettaskuser1($wid){
		$sql ="SELECT p.pid as uid,u.user_name as name,u.user_account  FROM t_mount_guard p LEFT JOIN t_user u ON u.PID =p.pid  WHERE p.wid ={$wid} AND p.status = 1";
		return $res = $this->M_device->querylist($sql);
	}

	/*
	*查询作业人员的接收人
	*$wid 岗位id
	*/
	private  function gettaskuser2($wid){
		$sql = "SELECT p.user_id,u.user_account FROM t_work_person p LEFT JOIN t_user u ON u.user_id =p.user_id WHERE p.post_id ={$wid}";
 		return $res = $this->M_device->querylist($sql);
	}
	//扫码获取设备信息
	/**
	 *@param $PID  用户id
	 *@param $number  设备编码
	 */
	public function get_device_info(){
		$userid = $this->input->get_post("userid", true);//用户id
		$number = $this->input->get_post("number", true);//设备编码
		if(empty($number)){
		       exit(json_encode(array('code'=>1,'info'=>'设备编码不能为空！')));
		}
		$sql = "select device_id,device_name,device_type_id,grid_id from t_device where device_number='{$number}'";
		$list = $this->db->query($sql)->row_array();
			if(!empty($list)){
				$this->printJson_data($list);
			}else{
				exit(json_encode(array('code'=>1,'info'=>'无此设备,需手动录入设备信息!')));
			}
	}
	//根据设备类型和设备位置查询设备名称
	/**
	 *@param $pid  用户id
	 *@param $typename  设备类型名称
	 *@param $place  设备位置名称
	 */
	public function get_devicename(){
		$userid = $this->input->get_post("userid", true);//用户id
		$typeid = $this->input->get_post("typeid", true);//设备类型ID
		$grid = $this->input->get_post("grid", true);//设备网格ID
		// $typename = '空调';
		// $grid = '一候客运';
		if(empty($typeid)){
		       exit(json_encode(array('code'=>1,'info'=>'设备类型ID不能为空')));
		}
		if(empty($grid)){
		       exit(json_encode(array('code'=>1,'info'=>'所属网格不能为空')));
		}
		$sql = "select device_id,device_name,device_type_id,grid_id from t_device where device_type_id='{$typeid}' and grid_id='{$grid}'";
		$list = $this->M_device->querylist($sql);
		if(!empty($list)){
			$this->printJson_data($list);
		}else{
			exit(json_encode(array('code'=>1,'info'=>'无相关设备')));
		}
	}
	//获取所有类型
	public function get_device_type(){
		$sql = "SELECT device_type_id,device_type_name FROM t_device_type";
		$devicdtype = $this->M_device->querylist($sql);
		if(!empty($devicdtype)){
			$this->printJson_data($devicdtype);
		}else{
			exit(json_encode(array('code'=>1,'info'=>'无设备类型')));
		}
	}
	//获取所有位置
	public function get_device_grid(){
		$sql = "SELECT grid_id,grid_name,g.area_id,a.area_name FROM t_grid g LEFT JOIN t_area a on g.area_id=a.area_id";
		$sql1 = "SELECT * FROM t_area";
		$area = $this->M_device->querylist($sql1);
		$devicdgrid = $this->M_device->querylist($sql);

		foreach ($area as $key => $val) {
		    foreach ($devicdgrid as $k => $v) {
		        if($val['area_id'] == $v['area_id'])
		        {
		            unset($v['area_id']);
		            $area[$key]['son'][] = $v;
		        }
		    }
		}
		
		if(!empty($area)){
			$this->printJson_data($area);
		}else{
			exit(json_encode(array('code'=>1,'info'=>'设备位置为空')));
		}
	}
	
	/**
	 * 设备维修/验收任务列表
	 * @param $PID  用户id
	 * @return string
	 * @throws cusException
	 * 
	*/
	public function get_device_tasklist(){
	             $userid = $this->input->get_post("userid", true);//用户id
	             $type = $this->input->get_post("type", true);//1验收2维修
	             $size 	= getParam($this->input->get("size", true), 'int', 20);  //条数
       		$page 	= getParam($this->input->get("page", true), 'int', 1);  //页数
       		$limit  = ($page - 1) * $size;
		$limit  .=",{$size}";
	             $tables =array('1'=>'t_device_inspecttask','2'=>'t_device_repairtask');
	             if(empty($userid)){
	        	             exit(json_encode(array('code'=>1,'info'=>'用户id不能为空!')));
	             }
	             if(empty($type)){
	        	             exit(json_encode(array('code'=>1,'info'=>'类型不能为空!')));
	             }
	             $table =$tables[$type];
	             if($type==2){
         			$sql = "SELECT d.device_name,r.report_remark,r.report_file,r.report_voice,t.device_type_name,g.grid_name,k.repairtask_id as taskid,tt.flag,k.repairtask_time as time FROM {$table} k LEFT JOIN t_device_report r on r.report_id=k.report_id LEFT JOIN t_device_task tt on tt.repairtask_id=k.repairtask_id LEFT JOIN t_device d on d.device_id=r.device_id LEFT JOIN t_device_type t on t.device_type_id=d.device_type_id LEFT JOIN t_grid g on g.grid_id=d.grid_id WHERE tt.user_id={$userid} AND tt.the_task_type=2 ORDER BY k.repairtask_time DESC limit {$limit}";
	             }else{
	             	$sql = "SELECT d.device_name,r.report_remark,r.report_file,r.report_voice,t.device_type_name,g.grid_name,k.inspecttask_id as taskid,tt.flag,k.inspecttask_time as time FROM {$table} k LEFT JOIN t_device_report r on r.report_id=k.report_id LEFT JOIN t_device_task tt on tt.inspecttask_id=k.inspecttask_id LEFT JOIN t_device d on d.device_id=r.device_id LEFT JOIN t_device_type t on t.device_type_id=d.device_type_id LEFT JOIN t_grid g on g.grid_id=d.grid_id WHERE tt.user_id={$userid} AND tt.the_task_type=1 ORDER BY k.inspecttask_time DESC limit {$limit}";
	             }
	    
	             $data = $this->M_device->querylist($sql);   
	             $this->printJson_data($data);
	}
	
	/**设备故障上报记录
	 *@param $PID
	*/
	public function device_report_list(){
			$userid = $this->input->get_post("userid", true);//用户id
			$type = $this->input->get_post("type", true);// 1上报记录  2任务列表
			$size 	= getParam($this->input->get("size", true), 'int', 20);  //条数
       			$page 	= getParam($this->input->get("page", true), 'int', 1);  //页数
			if(empty($userid)){
			       exit(json_encode(array('code'=>1,'info'=>'用户pid不能为空')));
			}
			if(empty($type)){
			       exit(json_encode(array('code'=>1,'info'=>'类型不能为空')));
			}
			$limit  = ($page - 1) * $size;
			$limit  .=",{$size}";
			$data   = array('total_page' => "0", 'data' => array());
        			// $data['total_page'] = ceil($count / $size);
			//1只能看到自己上报的记录2看到车间所有的的设备记录
			if($type==1){
				$sql = "select r.report_status,r.report_remark,r.report_id,r.report_addtime,d.device_name from t_device_report r LEFT JOIN t_device d ON d.device_id=r.device_id  where report_user_id='{$userid}'  order by report_addtime DESC limit {$limit}";
				$sql1 = "select count(*) as count from (select r.report_status,r.report_remark,r.report_id,r.report_addtime,d.device_name from t_device_report r LEFT JOIN t_device d ON d.device_id=r.device_id  where report_user_id='{$userid}'  order by report_addtime DESC) a  ";
				$count = $this->db->query($sql1)->row_array();
				// $data['total_page'] = ceil($count['count'] / $size);
				$res = $this->M_device->querylist($sql);
				// $data['data'] = $res;
			}else{
				$sqldet="SELECT user_id,department_id FROM t_user WHERE user_id={$userid}";
				$det = $this->M_device->querylist($sqldet);
				$ty=array();
				if(!empty($det)){
					foreach ($det as $key => $value) {
							$sqlty="select device_type_id,device_type_name from t_device_type where department_id='{$value['department_id']}'";
							$tyl = $this->M_device->querylist($sqlty);
							foreach ($tyl as $key1 => $value1) {
								array_push($ty, $value1);
							}
					}
				}
				if(!empty($ty)){
					$res=array();
					foreach ($ty as $key2 => $value2) {
						$sql = "select r.report_status,r.report_remark,r.report_id,r.report_addtime,d.device_name from t_device_report r left join t_device d on d.device_id=r.device_id where r.device_type_id='{$value2['device_type_id']}' order by report_addtime DESC limit {$limit}";
						$list = $this->M_device->querylist($sql);
						$sql1="select count(*) as count from (select r.report_status,r.report_remark,r.report_id,r.report_addtime,d.device_name from t_device_report r left join t_device d on d.device_id=r.device_id where r.device_type_id='{$value2['device_type_id']}' order by report_addtime DESC) a";
						$count = $this->db->query($sql1)->row_array();
						if(!empty($list)){
							foreach ($list as $key3 => $value3) {
								array_push($res, $value3);
							}
						}
					}
					if(!empty($res)){
						foreach ($res as $row_array)
						{  
							$key =  $row_array['report_addtime'];
							$key_array[] = $key;
						}  
						array_multisort($key_array,SORT_DESC,$res);
					}
					// $data['total_page'] = ceil($count['count'] / $size);
					// $data['data'] = $res;

				}
				// else{
				// 	$sql = "select r.*,d.device_name from t_device_report r LEFT JOIN t_device d ON d.device_id=r.device_id  where report_user_id='{$userid}'  order by report_addtime DESC";
				// 	$res = $this->M_device->querylist($sql);
				// }
			}
	
			$this->printJson_data($res);
		
	}
	/**设备故障上报详情
	 *@param $PID
	 *@param $mtid
	 */
	public function device_report_details(){
			$userid = $this->input->get_post("userid", true);//用户id
			$reportid = $this->input->get_post("reportid", true);//上报ID
			if(empty($userid)){
			       exit(json_encode(array('code'=>1,'info'=>'用户pid不能为空')));
			}
			if(empty($reportid)){
			       exit(json_encode(array('code'=>1,'info'=>'设备维护reportid不能为空！')));
			}
			$sql = "select d.device_name,r.report_remark,t.device_type_name,g.grid_name,r.report_file,r.report_voice,r.report_status from t_device_report r left join t_device d on d.device_id=r.device_id left join t_device_type t on t.device_type_id=r.device_type_id left join t_grid g on g.grid_id=d.grid_id where report_id={$reportid}";
			$list = $this->db->query($sql)->row_array(); //上报的信息  设备名称  留言  附件  语音 上报状态
			if($list['report_status']==1 || $list['report_status']==2 || $list['report_status']==3 || $list['report_status']==4){
				$sql = "SELECT report_user_name,report_addtime,report_remark FROM t_device_report WHERE report_id={$reportid}";
				$list1 = $this->db->query($sql)->row_array();
				$sql1 = "SELECT u.user_name,t.task_result,t.task_addtime,t.task_donetime,t.task_remark FROM t_device_repairtask k LEFT JOIN t_device_report r ON r.report_id=k.report_id LEFT JOIN t_device_task t ON t.repairtask_id=k.repairtask_id LEFT JOIN t_user u ON u.user_id=t.user_id WHERE r.report_id={$reportid} AND the_task_type=2";
				$list2 = $this->db->query($sql1)->row_array();
				$sql2 = "SELECT u.user_name,t.task_result,t.task_addtime,t.task_donetime,t.task_remark FROM t_device_inspecttask i LEFT JOIN t_device_report r ON r.report_id=i.report_id LEFT JOIN t_device_task t ON t.inspecttask_id=i.inspecttask_id LEFT JOIN t_user u ON u.user_id=t.user_id WHERE r.report_id={$reportid} AND the_task_type=1";
				$list3 = $this->db->query($sql2)->row_array();
			}
			if(!empty($list1)){
				$data = array(
						array(
						'status'=>"1",
		                                                    'username'=>$list1['report_user_name'],
		                                                    'addtime'=>$list1['report_addtime'],
		                                                    'remark'=>$list1['report_remark'],
		                                                    'result'=>"1",
		                                                    ),

					);
			}
			if(!empty($list2)){
				$data = array(
						array(
						'status'=>"1",
		                                                    'username'=>$list1['report_user_name'],
		                                                    'addtime'=>$list1['report_addtime'],
		                                                    'remark'=>$list1['report_remark'],
		                                                    'result'=>"1",
		                                                    ),
						array(
						'status'=>"2",
						'username'=>$list2['user_name'],
						'addtime'=>empty($list2['task_donetime'])?$list2['task_addtime']:$list2['task_donetime'],
						'remark'=>$list2['task_remark'],
						'result'=>$list2['task_result'],
						),

					);
			}
			if(!empty($list3)){
				$data = array(
						array(
						'status'=>"1",
		                                                    'username'=>$list1['report_user_name'],
		                                                    'addtime'=>$list1['report_addtime'],
		                                                    'remark'=>$list1['report_remark'],
		                                                    'result'=>"1",
		                                                    ),
						array(
						'status'=>"2",
						'username'=>$list2['user_name'],
						'addtime'=>empty($list2['task_donetime'])?$list2['task_addtime']:$list2['task_donetime'],
						'remark'=>$list2['task_remark'],
						'result'=>$list2['task_result'],
						),
						array(
						'status'=>"3",
						'username'=>$list3['user_name'],
						'addtime'=>empty($list3['task_donetime'])?$list3['task_addtime']:$list3['task_donetime'],
						'remark'=>$list3['task_remark'],
						'result'=>$list3['task_result'],
						),

					);
			}
			$res=array();
			$res['devinfo']=$list;
			$res['taskinfo']=$data;
			$this->printJson_data($res);
	}
	
	/**
	 * 接收设备任务
	 * @param $PID 用户id
	 * @param $type  类型
	 * @param $tid 任务ID
	 * @return string
	 * @throws cusException
	 */
	public function save_device_task(){
	             $userid = $this->input->get_post("userid", true);//用户id
	             $type = $this->input->get_post("type", true);//类型
	             $tid = $this->input->get_post("tid", true);//任务ID
	             $flag = $this->input->get_post('flag',true); //是否可以接收 2超出 1 接收
		$tables =array('1'=>'t_device_inspecttask','2'=>'t_device_repairtask');
		$taskids = array('1'=>'inspecttask_id','2'=>'repairtask_id');
		if(empty($userid)){
		        exit(json_encode(array('code'=>1,'info'=>'用户pid不能为空!')));
		}
		if(empty($type)){
		        exit(json_encode(array('code'=>1,'info'=>'任务类型不能为空!')));
		}
		if(empty($tid)){
		        exit(json_encode(array('code'=>1,'info'=>'任务ID不能为空!')));
		}
		if(empty($flag)){
		        exit(json_encode(array('code'=>1,'info'=>'flag不能为空!')));
		}
		if($flag==2){
			$sql = "UPDATE t_device_task SET flag=2,task_status=2 WHERE repairtask_id={$tid}";
			$res = $this->db->query($sql);
			if($res){
				exit(json_encode(array('code'=>0,'info'=>'已报给指挥中心!')));
			}

                                      //超出职能范围推送给车间负责人
		}else{
			$table =$tables[$type];
			$taskid = $taskids[$type];
			$sqlg = "select {$taskid} from {$table} where {$taskid}={$tid} and status<>1"; //状态为0未下发，2已接收，1未接受
			$g = $this->db->query($sqlg)->row_array(); 
			if(!empty($g)){
				exit(json_encode(array('code'=>1,'info'=>'任务无法接收,请重新刷新!')));
			}
			//接受任务 报修改维修 上报状态改为维修 接收人的flag 为1进行中 task_status1已接收
			if($type == 2){
				$sqlg2 = "select k.report_id,r.device_id from t_device_repairtask k left join t_device_report r on r.report_id=k.report_id where repairtask_id={$tid}";
				$gg = $this->db->query($sqlg2)->row_array(); 
				// var_dump($gg);exit();
				if(!empty($gg)){
					$de_id = $gg['device_id']; //设备ID
					$re_id = $gg['report_id']; //上报ID
					//修改设备状态
					$sql_dev ="update t_device SET device_status=3 WHERE device_id = {$de_id}";
					$this->db->query($sql_dev); 
					//修改上报表状态
					$sql_re = "update t_device_report SET report_status=2 WHERE report_id = {$re_id}";
					$this->db->query($sql_re); 
					//修改任务接受人的状态
					$sql = "UPDATE t_device_task SET task_status=1,flag=1,task_time=".time()." WHERE repairtask_id ={$tid} AND the_task_type={$type} AND user_id = {$userid}";
					$this->db->query($sql); 
					//删除其他接受人
					$sql2 ="delete from t_device_task where repairtask_id ={$tid}  AND task_status =0 AND the_task_type={$type}";
					$this->db->query($sql2); 
					//修改任务状态
					$opsql ="UPDATE {$table} set status=2 where {$taskid}={$tid}";
					$list = $this->db->query($opsql); 
				} 
			}else{
			    	$sqlg2 = "select k.report_id,r.device_id from t_device_inspecttask k left join t_device_report r on r.report_id=k.report_id where inspecttask_id={$tid}";
				$gg = $this->db->query($sqlg2)->row_array();
				if(!empty($gg)){
					$de_id = $gg['device_id']; //设备ID
					$re_id = $gg['report_id']; //上报ID
					//修改设备状态
					$sql_dev ="update t_device SET device_status=4 WHERE device_id = {$de_id}";
					$this->db->query($sql_dev); 
					//修改上报表状态
					$sql_re = "update t_device_report SET report_status=3 WHERE report_id = {$re_id}";
					$this->db->query($sql_re); 
					//修改任务接受人的状态
					$sql = "UPDATE t_device_task SET task_status=1,flag=1,task_time=".time()." WHERE inspecttask_id ={$tid} AND the_task_type={$type} AND user_id = {$userid}";
					$this->db->query($sql); 
					//删除其他接受人
					$sql2 ="delete from t_device_task where inspecttask_id ={$tid}  AND task_status =0 AND the_task_type={$type}";
					$this->db->query($sql2); 
					//修改任务状态
					$opsql ="UPDATE {$table} set status=2 where {$taskid}={$tid}";
					$list = $this->db->query($opsql); 
				} 
			}
		}
		if(!empty($list)){
		exit(json_encode(array('code'=>0,'info'=>'接收成功!')));
			// $this->printJson_data($info='接收成功');
		}
	}
	/**
	 * 设备维修结果
	 * @param $info
	 * @return string
	 * @throws cusException
	 * $info = array(
	 *			"keycode" => "gzRN53VWRF9BYUXo",//密钥
	 * 			"pid" =>64,//用户id
	 *          "typename"=>//设备类型名称
	 * 			"tid" =>1,//任务id
	 * 			"filepath"=>,//附件
	 * 			"filename"=>,//附件名称
	 *          "remarktype"=>,//0-文字,1-语音
	 * 			"remark"=>,//留言
	 * 			"result"=>,//2-故障未排除 1-故障已排除 3-超出工作职能范围
	 *          "typeid"=>//设备类型id
	 * )
	*/
	public function get_repairedevice_result(){
		$userid = $this->input->get_post("userid", true);//用户id
		$tid = $this->input->get_post("tid", true);//任务id
		$result = $this->input->get_post("result", true);// 结果  1排除  2未排除 3超出只能范围
		$taskremark = $this->input->get_post("taskremark", true);// 留言
		$taskvoice = $this->input->get_post("taskvoice", true);// 语音
		$taskfile = $this->input->get_post("taskfile", true);// 文件
		if(empty($userid)){
		        exit(json_encode(array('code'=>1,'info'=>'用户pid不能为空!')));
		}
		if(empty($tid)){
		        exit(json_encode(array('code'=>1,'info'=>'任务id不能为空!')));
		}
		if(empty($result)){
		        exit(json_encode(array('code'=>1,'info'=>'结果不能为空!')));
		}

		$now=time();
		$sql = "UPDATE t_device_repairtask set repairtask_result='{$result}' where repairtask_id={$tid}";
		$re =$this->db->query($sql);
		$sql1 = "UPDATE t_device_task set task_file='{$taskfile}',task_voice='{$taskvoice}',task_remark='{$taskremark}',task_donetime='{$now}',task_result='{$result}',flag=2 where repairtask_id={$tid} and user_id='{$userid}' and the_task_type=2 and task_result=0";
		$re1 =$this->db->query($sql1);
		if($re&&$re1){
			//1.设备表不存在的设备,通知任务发起人 2.存在的设备,通知车间所有负责人
			$sql1 = "select a.report_id,a.device_type_id,b.repairtask_user_id,d.device_id from t_device_report a left join t_device_repairtask b on a.report_id=b.report_id LEFT JOIN t_device d on d.device_id=a.device_id where b.repairtask_id='{$tid}'";
			$res1=$this->db->query($sql1)->row_array();
			$sql3 ="SELECT user_name FROM t_user WHERE user_id= '{$userid}'";
			$users3 = $this->db->query($sql3)->row_array();
			if($result==1){
				$a='设备故障已排除';
			}
			if($result==2){
				$a='设备故障未排除';
			}
			if(empty($res1['device_id'])){
				$sql2 ="SELECT user_name FROM t_user WHERE user_id= '{$res1['repairtask_user_id']}'";
				$users = $this->db->query($sql2)->row_array();
				if(!empty($users)){
					$title ='设备维修结果上报';
					$content=$a;
					// $url ="/plugins/devicemaintain/detail?id=".$res1['repairtask_user_id'];

					// $send = self::sendmess($users3['LoginName'],$content,$users['LoginName'],$title,$url,'devicenotice');	
				}	
			}else{
				//通知车间负责人
				$sqld = "select department_id from t_device_type where device_type_id='{$res1['device_type_id']}'";
				$dept = $this->db->query($sqld)->row_array();
				if(!empty($dept)){
					$sqlp = "select user_id from t_user where user_level=2 and department_id='{$dept['department_id']}'";
					$chargep = $this->M_device->querylist($sqlp);
					if(!empty($chargep)){
						// $chargestr=$chargep['principal'];
						// $chargearr=explode(',', $chargestr);
						foreach ($chargep as $key => $value) {
								$sql2 ="SELECT user_name FROM t_user WHERE user_id= '{$value['user_id']}'";
								$users = $this->db->query($sql2)->row_array();
								$title ='设备维修结果上报';
								$content=$a;
								// $url ="/plugins/devicemaintain/detail?id=".$res1['repairtask_user_id'];
								// $send = self::sendmess($users3['LoginName'],$content,$users['LoginName'],$title,$url,'devicenotice');
						}
					}
				}
			}
	        		exit(json_encode(array('code'=>0,'info'=>'保存成功!')));
			
			// return method::output(1,'保存成功','500',$Json);
		}
		exit(json_encode(array('code'=>1,'info'=>'保存失败!')));

	// return method::output(0,'保存失败','501',$Json);

}
	/**
	 * 设备验收结果
	 * @param $info
	 * @return string
	 * @throws cusException
	 * $info = array(
	 *			"keycode" => "gzRN53VWRF9BYUXo",//密钥
	 * 			"pid" =>64,//用户id
	 * 			"tid" =>1,//任务id
	 * 			"filepath"=>,//附件
	 * 			"filename"=>,//附件名称
	 *          "remarktype"=>,//0-文字,1-语音
	 * 			"remark"=>,//留言
	 * 			"result"=>,//2-不合格 1-合格
	 * )
	 */
	public function get_inspectdevice_result(){
		$userid = $this->input->get_post("userid", true);// 验收人id
		$tid = $this->input->get_post("tid", true);// 任务id
		$result = $this->input->get_post("result", true);// 结果1合格2不合格
		$taskfile = $this->input->get_post("taskfile", true);// 文件
		$taskvoice = $this->input->get_post("taskvoice", true);// 语音
		$taskremark = $this->input->get_post("taskremark", true);// 留言
		if(empty($userid)){
		        exit(json_encode(array('code'=>1,'info'=>'用户pid不能为空!')));
		}
		if(empty($tid)){
		        exit(json_encode(array('code'=>1,'info'=>'任务tid不能为空！!')));
		}
		if(empty($result)){
		        exit(json_encode(array('code'=>1,'info'=>'任务结果不能为空！!')));
		}
			$now=time();
			$sql = "UPDATE t_device_inspecttask set inspecttask_result='{$result}' where inspecttask_id={$tid}";
			$re =$this->db->query($sql);
			$sql1 = "UPDATE t_device_task set task_remark='{$taskremark}',task_voice='{$taskvoice}',task_file='{$taskfile}',task_donetime='{$now}',task_result='{$result}',flag=2 where inspecttask_id={$tid} and user_id='{$userid}' and the_task_type=1 and task_result=0";
			$re1 =$this->db->query($sql1);
			if($re&&$re1){
				$sql1 = "select a.report_id,a.device_id,a.report_status,a.report_user_id,d.device_name,g.grid_name,b.inspecttask_user_id from t_device_report a left join t_device_inspecttask b on a.report_id=b.report_id left join t_device d on d.device_id=a.device_id left join t_grid g on g.grid_id=d.grid_id where b.inspecttask_id='{$tid}'";
				$res1=$this->db->query($sql1)->row_array();
				// var_dump($res1);exit();
				$sql3 ="SELECT user_name FROM t_user WHERE user_id= '{$userid}'";
				$users3 = $this->db->query($sql3)->row_array();
				$sql2 ="SELECT user_name FROM t_user WHERE user_id= '{$res1['inspecttask_user_id']}'";
				$users = $this->db->query($sql2)->row_array();
				$sql4 ="SELECT user_name FROM t_user WHERE user_id= '{$res1['report_user_id']}'";
				$users4 = $this->db->query($sql4)->row_array();
				if($result==1){
					$a='设备验收已合格';
				}
				if($result==2){
					$a='设备验收不合格';
				}
				if($result==1){//发送通知报修人和任务发起人
					if(!empty($res1)){
						//维修设备完成,更新设备状态 上报任务状态为完成
						if($res1['report_status']==3){
							$usql="update t_device set device_status=1 where device_id='{$res1['device_id']}'";
							$ure =$this->db->query($usql);
							$usql1="update t_device_report set report_flag=1,report_status=4 where report_id='{$res1['report_id']}'";
							$ure1 =$this->db->query($usql1);
						}else{
							// $usql="update t_device_report set status=1,flag=1 where id='{$res1['id']}'";
							// $ure =$handModel->db->query($usql);
						}
						// $title ='设备验收结果上报';
						// $content=$res1['place'].'处'.$res1['name'].'已维修完成';
						// $url = "/plugins/devicemaintain/detail?id=".$res1['id'];//设备上报故障列表
						
						// $send = self::sendmess($users3['LoginName'],$content,$users4['LoginName'],$title,$url,'devicenotice');
						// $send1 = self::sendmess($users3['LoginName'],$content,$users['LoginName'],$title,$url,'devicenotice');
					}
				}else{
					//发送通知任务发起人
					// $title ='设备验收结果上报';
					// $content=$a;
					// $url = "/plugins/devicemaintain/detail?id=".$res1['id'];//设备上报故障列表
					// $send1 = self::sendmess($users3['LoginName'],$content,$users['LoginName'],$title,$url,'devicenotice');
				}
		    		exit(json_encode(array('code'=>0,'info'=>'保存成功!')));

				// return method::output(1,'保存成功','500',$Json);
			}
	    		exit(json_encode(array('code'=>1,'info'=>'保存失败!')));

			// return method::output(0,'保存失败','501',$Json);
		
	}

	/**
	 * 下发设备验收任务
	 * @param $info
	 * @return string
	 * @throws cusException
	 * $info = array(
	 *			"keycode" => "gzRN53VWRF9BYUXo",//密钥
	 * 			"pid" =>64,//用户id，
	 *			"mtid" =>//设备维护id
	 *			
	 *          "uid"=>//接收人
	 *          "endtime"=>//任务完成时间
	 *          "remark"=>//说明
	 * )
	 */
	public function save_inspecttask(){
	             $userid = $this->input->get_post("userid", true);//下发人id
	             $reportid = $this->input->get_post("reportid", true);//上报
	             $pubid = $this->input->get_post("pubid", true);//接收人id
	             $taskendtime = $this->input->get_post("taskendtime", true);//任务要求完成时间
		if(empty($userid)){
		        exit(json_encode(array('code'=>1,'info'=>'用户id不能为空！!')));
		}
		if(empty($reportid)){
		        exit(json_encode(array('code'=>1,'info'=>'设备维护reportid不能为空！!')));
		}
		if(empty($pubid)){
		        exit(json_encode(array('code'=>1,'info'=>'任务接收人不能为空！!')));
		}
		if(empty($taskendtime)){
		        exit(json_encode(array('code'=>1,'info'=>'任务截止时间不能为空！!')));
		}
		$sql = "select * from t_device_report where report_id='{$reportid}'"; 
		$list = $this->db->query($sql)->row_array();
			if($list['report_user_id']==$userid){
				$sqld = "select department_id from t_device_type where device_type_id='{$list['device_type_id']}'";
				$dept = $this->db->query($sqld)->row_array();
				if(!empty($dept)){
					$sqlp = "SELECT department_id FROM t_user WHERE department_id={$dept['department_id']} AND user_level=2 AND user_id={$userid}";
					$chargep = $this->db->query($sql)->row_array();
					if(empty($chargep)){
		        				exit(json_encode(array('code'=>1,'info'=>'对不起,您无权限验收任务!')));
					}
				}
			}
			$sqlp = "select user_name from t_user where user_id='{$userid}'";
			$p = $this->db->query($sqlp)->row_array();
			$idstr=$pubid;
			$idarr=explode(',', $idstr);
			$sql2 = "select repairtask_result from t_device_repairtask where report_id='{$reportid}'"; 
			$list2 = $this->db->query($sql2)->row_array();
			$sql3 = "select inspecttask_id from t_device_inspecttask where report_id='{$reportid}'"; 
			$list3 = $this->db->query($sql3)->row_array();
			if($list['report_flag']==0&&$list['report_status']==2&&$list2['repairtask_result']==1){
				if(empty($list3)){
					$data1=array(
						'inspecttask_user_id'=>$userid,
						'inspecttask_result'=>0,
						'inspecttask_time'=>time(),
						'status'=>0,
						'inspecttask_is_open'=>0,
						'report_id'=>$reportid
						);
					$insert_id1 = $this->M_device_inspecttask->saveData($data1);
				}else{
					$insert_id1 = $list3['inspecttask_id'];
				}
				if($insert_id1){
					foreach ($idarr as $key => $value) {
						if($value){
						$data2=array(
						'inspecttask_id'=>$insert_id1,
						'the_task_type'=>1,
						'user_id'=>$value,
						'task_status'=>0,
						'task_time'=>0,
						'task_addtime'=>time(),
						'task_endtime'=>$taskendtime,
						);
					$insert_id2 = $this->M_device_task_sub->saveData($data2);
					// $url ="#";//维修任务列表
					// $type ="deviceexaminenotice";
					// $content = $list['report_remark'];
					// $title = $list['name'].'设备的验收任务';//设备名称
					// $send = self::sendmess($p['LoginName'],$content,$det['LoginName'],$title,$url,$type);
						}
					}
					$nowtime=time();//任务发布时间
					//修改任务状态
					$updsql = "UPDATE t_device_inspecttask SET status=1,inspecttask_is_open=1,inspecttask_result=0,inspecttask_user_id='{$userid}',inspecttask_time='{$nowtime}' WHERE inspecttask_id='{$insert_id1}'";
					$this->db->query($updsql);

					$updsql1 = "UPDATE t_device_report SET report_status=3 WHERE report_id ='{$reportid}'";
					$this->db->query($updsql1);
		        			exit(json_encode(array('code'=>0,'info'=>'验收任务下发成功!')));
				}
			}
			exit(json_encode(array('code'=>1,'info'=>'验收任务下发失败!')));
	
	}
	
	/**
	 * 下发设备维修任务
	 * @param $info
	 * @return string
	 * @throws cusException
	 */
	public function save_repairtask(){
		$userid = $this->input->get_post("userid", true);//下发人
		$reportid = $this->input->get_post("reportid", true);//结果1维修好了2故障
		$uid = $this->input->get_post("pubid", true);//接收人
		$endtime = $this->input->get_post("endtime", true);//反馈内容
		if(empty($userid)){
		       exit(json_encode(array('code'=>1,'info'=>'用户pid不能为空')));
		}
		if(empty($reportid)){
		       exit(json_encode(array('code'=>1,'info'=>'设备维护reportid不能为空')));
		}
		if(empty($uid)){
		       exit(json_encode(array('code'=>1,'info'=>'任务接收人不能为空')));
		}
		if(empty($endtime)){
		       exit(json_encode(array('code'=>1,'info'=>'任务截止时间不能为空')));
		}
		$sql = "select * from t_device_report where report_id='{$reportid}'"; 
		$list = $this->db->query($sql)->row_array();
		if($list['report_user_id']==$userid){
			$sqld = "select department_id from t_device_type where device_type_id='{$list['device_type_id']}'";
			$dept = $this->db->query($sqld)->row_array();
			if(!empty($dept)){
				$sqlp = "SELECT department_id FROM t_user WHERE department_id='{$dept['department_id']}' AND  user_level=2";
				$chargep = $this->M_device->querylist($sqlp);
				if(empty($chargep)){
		       			exit(json_encode(array('code'=>1,'info'=>'对不起,您无权限操作下发任务')));
				}
			}
		}
		$sqlp = "select user_name from t_user where user_id='{$userid}'";
		$p = $this->db->query($sqlp)->row_array();
			if($list['report_flag']==0&&$list['report_status']=1){
				$sqltid = "select repairtask_id from t_device_repairtask where report_id='{$reportid}'";
				$tid = $this->db->query($sqltid)->row_array();
				$taskid=$tid['repairtask_id'];
				$sqlr = "select * from t_device_task where repairtask_id='{$taskid}' and the_task_type=2 order by task_addtime DESC";
				$r = $this->M_device->querylist($sqlr);
				$sqlrid = "select inspecttask_id from t_device_inspecttask where report_id='{$reportid}'";
				$rtid = $this->db->query($sqlrid)->row_array();
				if(!empty($rtid)){
					$sqlg = "select * from t_device_task where inspecttask_id='{$rtid['inspecttask_id']}' and the_task_type=1 order by task_addtime DESC";
					$g = $this->M_device->querylist($sqlg);
					if(!empty($g)){
						foreach ($g as $key => $value) {
							array_push($r, $value);
						}
					}
				}
				if(!empty($r)){
					$sort_key='task_addtime';
					foreach ($r as $row_array)
					{  
						$key =  $row_array[$sort_key];
						$key_array[] = $key;
					}  
					array_multisort($key_array,SORT_DESC,$r);
				}
				$sqlr = "select task_id,task_status,task_result,the_task_type from t_device_task where repairtask_id='{$taskid}' and the_task_type=2 and task_status=1 and task_result=0";
				$r = $this->M_device->querylist($sqlr);
				if(count($r)){
	       				exit(json_encode(array('code'=>1,'info'=>'此维修任务已经有人在做,无法下发!')));
				}
					$sqldet="select a.user_name,a.user_account,a.department_id,b.department_name from t_user a left join t_department b on b.department_id=a.department_id where a.user_id='{$uid}'";
					$det = $this->db->query($sqldet)->row_array();
					$data2=array(
					'repairtask_id'=>$taskid,
					'the_task_type'=>2,
					'user_id'=>$uid,
					'task_status'=>0,
					'task_time'=>0,
					'task_addtime'=>time(),
					'task_endtime'=>$endtime,
					);
				$insert_id2 = $this->M_device_task_sub->saveData($data2);
				// $url ="#";//维修任务列表
				// $type ="devicemaintainnotice";
				// $content = $Info['remark'];
				// $title = $list['name'].'设备维修任务';//设备名称
				// $send = self::sendmess($p['LoginName'],$content,$det['LoginName'],$title,$url,$type);
				$nowtime=time();
				//修改任务状态
				$updsql = "UPDATE t_device_repairtask SET status=1,repairtask_is_open=1,repairtask_result=0,repairtask_user_id='{$userid}',repairtask_time='{$nowtime}' WHERE repairtask_id='{$taskid}'";
				$this->db->query($updsql);
				$updsql1 = "UPDATE t_device_report SET report_status=2 WHERE report_id={$reportid}";
				$this->db->query($updsql1);
				$updsql1 = "UPDATE t_device SET device_status=3 WHERE device_id={$list['device_id']}";
				$this->db->query($updsql1);
	       			exit(json_encode(array('code'=>0,'info'=>'维修任务下发成功')));
			}
		       	exit(json_encode(array('code'=>1,'info'=>'维修任务下发失败')));
		
	}
	

          
             /**
	 * 设备维修详情
	 * @param $info
	 * @return string
	 * @throws cusException
	 * $info = array(
	 *			"keycode" => "gzRN53VWRF9BYUXo",//密钥
	 * 			"pid" =>135,//用户id
	 * 			"tid" =>139,//任务id
	 * 			"mtid"=>21,//设备维护id
	 * )
	 */
	// public static function get_repairedevice_details($Info){
	// 	try{
	// 		$Json = true;
	// 		$Message = method::validate($Info,$Json);
	// 		if (is_string($Message)){
	// 			return $Message;
	// 		}
	// 		$Info = $Message;
	// 		if(empty($Info['pid'])) return method::output(0, "用户pid不能为空！", '501', $Json);
	// 		if(empty($Info['tid'])) return method::output(0, "任务tid不能为空！", '501', $Json);
	// 		$handModel = Model::singleton('bjnz_device_repairtask');
	// 		$sql = "SELECT a.id, b.name, b.place,b.typename,b.remark,b.remarktype,b.filepath,b.filename,s.optime,s.endtime,u.UserName as pubname,s.addtime as pubtime
	// 		FROM t_bjnz_device_repairtask a 
	// 		LEFT JOIN t_bjnz_device_maintenance b ON b.id =  a.mtid 
	// 		LEFT JOIN t_bjnz_device_task_sub s ON a.id =s.taskid
	// 		LEFT JOIN t_user u on u.PID=a.pubuid
	// 		WHERE s.pid ={$Info['pid']} AND s.type =2 AND a.status =2 AND a.id={$Info['tid']} and b.id={$Info['mtid']}"; 
	// 		$list = $handModel->db->fetch($sql);
	// 		return method::output(1,$list,'500',$Json);
	// 	}catch (cusException $e){
	// 		return method::output(0,$e->getMessage(),'503',$Json);
	// 	}
	// }
	// /**
	//  * 设备验收详情
	//  * @param $info
	//  * @return string
	//  * @throws cusException
	//  * $info = array(
	//  *			"keycode" => "gzRN53VWRF9BYUXo",//密钥
	//  * 			"pid" =>64,//用户id
	//  * 			"tid" =>1,//任务id
	//  * 			"mtid"=>12,//设备维护id
	//  * )
	//  */
	// public static function get_inspectdevice_details($Info){
	// 	try{
	// 		$Json = true;
	// 		$Message = method::validate($Info,$Json);
	// 		if (is_string($Message)){
	// 			return $Message;
	// 		}
	// 		$Info = $Message;
	// 		if(empty($Info['pid'])) return method::output(0, "用户pid不能为空！", '501', $Json);
	// 		if(empty($Info['tid'])) return method::output(0, "任务tid不能为空！", '501', $Json);
	// 		$handModel = Model::singleton('bjnz_device_inspecttask');
	// 		$sql = "SELECT a.id, b.name, b.place,b.typename,b.remark,b.filepath,b.filename,b.remarktype,s.optime,s.endtime,u.UserName as pubname,s.addtime as pubtime
	// 		FROM t_bjnz_device_inspecttask a 
	// 		LEFT JOIN t_bjnz_device_maintenance b ON b.id =  a.mtid 
	// 		LEFT JOIN t_bjnz_device_task_sub s ON a.id =s.taskid
	// 		LEFT JOIN t_user u on u.PID=a.pubuid
	// 		WHERE s.pid ={$Info['pid']} AND s.type =1 AND a.status =2 AND a.id={$Info['tid']} and b.id={$Info['mtid']}"; 
	// 		$list = $handModel->db->fetch($sql);
	// 		return method::output(1,$list,'500',$Json);
	// 	}catch (cusException $e){
	// 		return method::output(0,$e->getMessage(),'503',$Json);
	// 	}
	// }

}